<template>
  <div class="home" ref="ardom">
    <div class="title">商品列表</div>
    <div class="modelList">
      <div
        class="modelListItem"
        v-for="({ thumb, url }, i) in modelList"
        :key="i"
      >
        <img class="img" :src="thumb" alt="" />
        <span class="btn" @click="activeXR(url)">AR查看</span>
      </div>
    </div>

    <!-- <canvas ref="bjsCanvas" width="400" height="300" /> -->
    <!-- <model-viewer
      is="model-viewer"
      style="width: 100%; height: 100%"
      src="./Chair.glb"
      ios-src="./robot.usdz"
      poster="./Chair.webp"
      shadow-intensity="1"
      ar
      camera-controls
      touch-action="pan-y"
      alt="A 3D model carousel"
    >
      <button slot="ar-button" id="ar-button">在您的共享空间中查看</button>

      <div id="ar-prompt">
        <img src="./hand.png" />
      </div>

      <button id="ar-failure">AR未跟踪!</button>
    </model-viewer> -->
    <!-- <div v-for="(item, i) in arInfo" :key="i">
      {{ item }}
    </div> -->
    <!-- <button @click="activeAR">进入安卓ar</button> -->
    <!-- &nbsp; -->
    <!-- <button @click="printXR">打印XR对象</button> -->
    <!-- <button class="ar" @click="activeXR">进入xr</button> -->
    <!-- &nbsp; -->
    <!-- <button @click="iosAR('/robot.usdz')">进入iosAR</button> -->
    <!-- <a
      :href="`intent://arvr.google.com/scene-viewer/1.2?file=${rootPath}/Chair.glb#Intent;scheme=https;package=com.google.android.googlequicksearchbox;action=android.intent.action.VIEW;S.browser_fallback_url=https://developers.google.com/ar;end;`"
      >View Model</a
    > -->
    <!-- <router-link to="/arcode">arcode demo</router-link> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import * as BABYLON from "@babylonjs/core";
import "@babylonjs/loaders/glTF/2.0";
import activeXR from "./activeXR";

const ardom = ref<HTMLCanvasElement | null>(null);
const arInfo = ref<Array<string>>([]);
//绝对路径
const rootPath = ref(import.meta.client ? location.origin : "");
const bjsCanvas = ref<HTMLCanvasElement | null>(null);

const modelList = ref([
  { thumb: "/Chair.webp", url: "/Chair.glb", arPlacement: "floor" },
  { thumb: "/fridgeThumb.png", url: "/fridge.glb", arPlacement: "floor" },
  { thumb: "/tvthumb.png", url: "/tv.glb", arPlacement: "wall" },
  {
    thumb: "/ceilling_lamp_thumb.png",
    url: "/ceilling_lamp.glb",
    arPlacement: "floor",
  },
]);

onMounted(async () => {
  if (import.meta.client) {
    import("vconsole").then(({ default: Vconsole }) => {
      if (ardom.value) {
        new Vconsole({
          target: ardom.value,
        });
      }
    });
  }

  if (bjsCanvas.value) {
    const engine = new BABYLON.Engine(bjsCanvas.value, true);
    const scene = new BABYLON.Scene(engine);

    // 创建相机
    const camera = (window.camera = new BABYLON.ArcRotateCamera(
      "camera",
      Math.PI / 2,
      Math.PI / 2,
      3,
      BABYLON.Vector3.Zero(),
      scene
    ));
    camera.attachControl(bjsCanvas.value, true);

    // 创建灯光
    const light = new BABYLON.HemisphericLight(
      "light",
      BABYLON.Vector3.Up(),
      scene
    );

    const { meshes, particleSystems, skeletons } =
      await BABYLON.SceneLoader.ImportMeshAsync(
        null, // 不加载特定的网格，加载整个文件
        "./fridge.glb", // GLB 文件的路径
        "",
        scene
      );

    // 创建立方体
    // const box = BABYLON.MeshBuilder.CreateBox("box", { size: 2 }, scene);
    // box.position.y = 1;

    // const env = scene.createDefaultEnvironment();
    // if (env) {
    //   const xr = await scene.createDefaultXRExperienceAsync({
    //     floorMeshes: [env.ground!],
    //   });
    // }

    // 初始化 WebXR 功能
    // const xrHelper = await scene.createDefaultXRExperienceAsync({
    //   uiOptions: {
    //     sessionMode: "immersive-vr",
    //   },
    //   optionalFeatures: ["hit-test", "anchors"],
    // });

    // 启用平面检测
    //   const baseExperience = xrHelper;
    //   const baseExperience = xrHelper.baseExperience;
    //   console.log("baseExperience",baseExperience);

    //   for (let key in baseExperience) {
    //       items.value.push(key);
    //   }

    //   const planeDetector = xrHelper.baseExperience.featuresManager.enableFeature(BABYLON.WebXRFeatureName.PLANE_DETECTION, "latest") as BABYLON.WebXRPlaneDetector;

    //   // 平面检测事件处理
    //   planeDetector.onPlaneAddedObservable.add((plane: BABYLON.IWebXRPlane) => {
    //     // 当检测到平面时，将立方体放置在平面上
    //     const position = plane.polygonDefinition.reduce((sum, point) => sum.add(point), BABYLON.Vector3.Zero()).scale(1 / plane.polygonDefinition.length);
    //     box.position = position;
    //     box.position.y = 0.5; // 确保立方体放置在平面上
    //   });

    engine.runRenderLoop(() => {
      scene.render();
    });

    window.addEventListener("resize", () => {
      engine.resize();
    });
  }
});
</script>

<style lang="less">
model-viewer {
  background-color: #eee;
  overflow-x: hidden;
}

#ar-button {
  background-image: url(../../assets/ic_view_in_ar_new_googblue_48dp.png);
  background-repeat: no-repeat;
  background-size: 20px 20px;
  background-position: 12px 50%;
  background-color: #fff;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  white-space: nowrap;
  bottom: 132px;
  padding: 0px 16px 0px 40px;
  font-family: Roboto Regular, Helvetica Neue, sans-serif;
  font-size: 14px;
  color: #4285f4;
  height: 36px;
  line-height: 36px;
  border-radius: 18px;
  border: 1px solid #dadce0;
}

#ar-button:active {
  background-color: #e8eaed;
}

#ar-button:focus {
  outline: none;
}

#ar-button:focus-visible {
  outline: 1px solid #4285f4;
}

@keyframes circle {
  from {
    transform: translateX(-50%) rotate(0deg) translateX(50px) rotate(0deg);
  }

  to {
    transform: translateX(-50%) rotate(360deg) translateX(50px) rotate(-360deg);
  }
}

@keyframes elongate {
  from {
    transform: translateX(100px);
  }

  to {
    transform: translateX(-100px);
  }
}

model-viewer > #ar-prompt {
  position: absolute;
  left: 50%;
  bottom: 175px;
  animation: elongate 2s infinite ease-in-out alternate;
  display: none;
}

model-viewer[ar-status="session-started"] > #ar-prompt {
  display: block;
}

model-viewer > #ar-prompt > img {
  animation: circle 4s linear infinite;
}

model-viewer > #ar-failure {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 175px;
  display: none;
}

model-viewer[ar-tracking="not-tracking"] > #ar-failure {
  display: block;
}

.slider {
  width: 100%;
  text-align: center;
  overflow: hidden;
  position: absolute;
  bottom: 16px;
}

.slides {
  display: flex;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
}

.slide {
  scroll-snap-align: start;
  flex-shrink: 0;
  width: 100px;
  height: 100px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  background-color: #fff;
  margin-right: 10px;
  border-radius: 10px;
  border: none;
  display: flex;
}

.slide.selected {
  border: 2px solid #4285f4;
}

.slide:focus {
  outline: none;
}

.slide:focus-visible {
  outline: 1px solid #4285f4;
}

.home {
  min-height: 100vh;
  background-color: #f0f0f0;
}

.title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  padding: 10px 0px;
}

.modelList {
  padding: 2px;

  &:after {
    content: "";
    clear: both;
    display: block;
  }
  .modelListItem {
    width: calc(50vw - 8px);
    padding: 2px;
    position: relative;
    float: left;
    .img {
      width: calc(50vw - 10px);
      height: calc(50vw - 10px);
      background-color: #ffffff;
      border-radius: 10px;
    }
    .btn {
      position: absolute;
      bottom: 10px;
      right: 10px;
      padding: 2px 10px 4px 10px;
      background-color: #ff6c6c;
      color: #ffffff;
      border-radius: 20px;
    }
  }
}
</style>
